/*
 * @Title Javajndi.java
 * @Description
 * @Copyright Copyright(c) 2018
 * @Company com.lizhen
 * @author lizhen
 * @version 0.0.1
 */
package com.lizhen.core.function.jndi;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import java.util.Hashtable;

/**
 * @author lizhen
 */
public class JNDI {

    /**
     * @author lizhen
     */
    public JNDI() {
    }

    /**
     * @author lizhen
     */
    public static void main(String[] args) {
        DNSQuery.main(new String[]{"sina.com"});
    }

    static class DNSQuery {

        public static void main(String[] args) {
            String domain = args[0];
            String dnsServer = args.length < 2 ? "" : "//" + args[1];
            Hashtable<String, String> env = new Hashtable<>();
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
            env.put(Context.PROVIDER_URL, "dns:" + dnsServer);
            try {
                DirContext ctx = new InitialDirContext(env);
                Attributes attrsAll = ctx.getAttributes(domain);
                Attributes attrsMx = ctx.getAttributes(domain, new String[]{"MX"});
/*	    DirContext ctx = new InitialDirContext();
	    Attributes attrsAll = ctx.getAttributes("dns:" + dnsServer + "/" + domain);
	    Attributes attrsMx = ctx.getAttributes( "dns:" + dnsServer + "/" + domain, new String[]{"MX"});
*/

                System.out.println(domain);
                System.out.println(attrsAll);
                System.out.println(attrsMx);

                NamingEnumeration<? extends Attribute> attributes = attrsAll.getAll();

                while (attributes.hasMore()) {
                    System.out.println(attributes.next());
                }

                Attribute attrMx = attrsMx.get("MX");
                String recordMx = (String) attrMx.get();
                String smtpServer = recordMx.substring(recordMx.indexOf(" ") + 1);

                System.out.println(attrMx);
                System.out.println(recordMx);
                System.out.println(smtpServer);
            } catch (NamingException e) {
                e.printStackTrace();
            }
        }

    }

}